<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace HyperfTest\Cases;

use App\Model\User;
use App\Request\UserLoginRequest;
use App\Service\Redis\SmsCollection;
use App\Service\Redis\UserAuth;
use Hyperf\Redis\Redis;
use HyperfTest\HttpTestCase;

/**
 * @internal
 * @coversNothing
 */
class UserTest extends HttpTestCase
{
    public function testUserRegister()
    {
        $mobile = '18678010000';
        di()->get(SmsCollection::class)->set($mobile, $code = rand(1000, 9999));
        $res = $this->json('/user/register', [
            'mobile' => $mobile,
            'type' => 1,
            'code' => (string) $code,
        ]);

        $this->assertSame(0, $res['code']);
        $this->assertNotEmpty($res['data']['token']);
    }

    public function testUserSave()
    {
        $res = $this->json('/user/save', [
            'nickname' => '测试人员',
            'gender' => User::GENDER_BOY,
            'avatar' => 'https://avatars2.githubusercontent.com/u/44228082?s=200&v=4',
            'birthday' => '1990-01-01',
            'education' => '本科',
            'intro' => '测试数据，用于单元测试',
        ], [
            UserAuth::X_TOKEN => $this->getToken(),
        ]);

        $this->assertSame(0, $res['code']);
    }

    public function testUserInfo()
    {
        $res = $this->get('/user/info', [], [
            UserAuth::X_TOKEN => $this->getToken(),
        ]);

        $this->assertSame(0, $res['code']);
    }

    public function testUserPassword()
    {
        $res = $this->json('/user/password', [
            'password' => md5('123456'),
        ], [
            UserAuth::X_TOKEN => $this->getToken(),
        ]);

        $this->assertSame(0, $res['code']);
        $this->assertTrue($res['data']['updated']);
    }

    public function testUserLogin()
    {
        $mobile = '18678010000';
        di()->get(Redis::class)->set('sms:' . $mobile, $code = rand(1000, 9999), 60);
        $res = $this->json('/user/login', [
            'mobile' => $mobile,
            'type' => UserLoginRequest::TYPE_CODE,
            'code' => (string) $code,
        ]);
        $this->assertSame(0, $res['code']);
        $this->assertArrayHasKey('id', $res['data']);
        $this->assertArrayHasKey('registered', $res['data']);
        $this->assertArrayHasKey('token', $res['data']);

        $mobile = '18678010000';
        $res = $this->json('/user/login', [
            'mobile' => $mobile,
            'type' => UserLoginRequest::TYPE_PASSWORD,
            'code' => md5('123456'),
        ]);
        $this->assertSame(0, $res['code']);
        $this->assertArrayHasKey('id', $res['data']);
        $this->assertArrayHasKey('registered', $res['data']);
        $this->assertArrayHasKey('token', $res['data']);
    }
}
